/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.hd4ic.gui.background;

import edu.hd4ic.algorithm.base.HDValue;
import edu.hd4ic.edu.hd4ic.data.ProcessingImageDataContainer;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;

/**
 * @author morfant
 */
public class DefaultHDValuesPresenter implements HDValuesPresenter {

    private final JTextArea textArea;
    private final String newLine = "\n";
    private final JButton calculateButton;
    private final Map<String, ProcessingImageDataContainer> inputImageMap;
    private final Map<String, ProcessingImageDataContainer> templateImageMap;
    private List<BufferedImage> inputImageWithFoundTemplateList = new LinkedList<BufferedImage>();
    private BufferedImage lastInputImageWithFoundTemplate = null;
    private String inputImageName = "";
    private String templateImageName = "";
    private JList inputImageList;
    private Workbook workbook;
    private Sheet mainSheet;
    private int rowNumber;
    private List<Color> listOfColor;
    private int numberOfColor;

//    private static HSS workbook;

    public DefaultHDValuesPresenter(JButton calculateButton, JTextArea textArea,
                                    Map<String, ProcessingImageDataContainer> inputImageMap,
                                    Map<String, ProcessingImageDataContainer> templateImageMap,
                                    JList inputImageList) {
        this.calculateButton = calculateButton;
        this.textArea = textArea;
        this.inputImageMap = inputImageMap;
        this.templateImageMap = templateImageMap;
        this.inputImageList = inputImageList;
        textArea.setText("");
        for (String inputImageFilePath : inputImageMap.keySet()) {
            inputImageMap.get(inputImageFilePath).setSearchResultImage(null);
        }
        this.workbook = new XSSFWorkbook();
        this.mainSheet = workbook.createSheet("Base Sheet");
        mainSheet.autoSizeColumn(0);
        this.rowNumber = 0;
        listOfColor = new ArrayList<Color>();
        listOfColor.add(new Color(0xFF0000, false));
        listOfColor.add(new Color(0xFFFF00, false));
        listOfColor.add(new Color(0xFF00FF, false));
        listOfColor.add(new Color(0x00FFFF, false));
        listOfColor.add(new Color(0x4CFF00, false));
        listOfColor.add(new Color(0x0026FF, false));
        listOfColor.add(new Color(0xB200FF, false));
        listOfColor.add(new Color(0x00A86B, false));
        listOfColor.add(new Color(0x4B0082, false));
        listOfColor.add(new Color(0x007F0E, false));
        numberOfColor = listOfColor.size();
    }

//    public DefaultHDValuesPresenter(JTextArea textArea,JButton calculateButton) {
//        this.textArea = textArea;
//        this.calculateButton=calculateButton;
//    }

    @Override
    public void showHDValues(List<HDValue> listOfHDValues) {
        int width, height, i, j, x, y, i_border, j_border;
        float r, g, b;
        templateImageName = "";
        Random random = new Random(System.currentTimeMillis());
        Color color = null;
        int usedColorNumber = 0;
        if (!listOfHDValues.isEmpty()) {
            inputImageName = listOfHDValues.get(0).getInputImageName();
            lastInputImageWithFoundTemplate = deepCopy((BufferedImage) inputImageMap.get(inputImageName).getInputImage());
            textArea.append(inputImageName + newLine);
            textArea.append("======================================" + newLine);
        }


        for (HDValue showingHDValue : listOfHDValues) {
            if (!showingHDValue.getTemplateImageName().equals(templateImageName)) {
                templateImageName = showingHDValue.getTemplateImageName();
//                r = random.nextFloat();
//                g = random.nextFloat();
//                b = random.nextFloat();
//                color = new Color(r, g, b);
//                color = color.brighter();
                color = listOfColor.get(usedColorNumber);
                usedColorNumber++;
                textArea.append(templateImageName + newLine);
            }

            ProcessingImageDataContainer templateImageContainer = templateImageMap.get(templateImageName);
            BufferedImage templateImage = (BufferedImage) templateImageContainer.getInputImage();
            width = templateImage.getWidth();
            height = templateImage.getHeight();
            x = showingHDValue.getX();
            y = showingHDValue.getY();
            i_border = width - 1;
            j_border = height - 1;

            for (i = 0; i < width; i++) {
                lastInputImageWithFoundTemplate.setRGB(i + x, 0 + y, color.getRGB());
                lastInputImageWithFoundTemplate.setRGB(i + x, j_border + y, color.getRGB());
                lastInputImageWithFoundTemplate.setRGB(i + x, 1 + y, color.getRGB());
                lastInputImageWithFoundTemplate.setRGB(i + x, j_border - 1 + y, color.getRGB());
            }
            for (j = 0; j < height; j++) {
                lastInputImageWithFoundTemplate.setRGB(0 + x, j + y, color.getRGB());
                lastInputImageWithFoundTemplate.setRGB(i_border + x, j + y, color.getRGB());
                lastInputImageWithFoundTemplate.setRGB(1 + x, j + y, color.getRGB());
                lastInputImageWithFoundTemplate.setRGB(i_border - 1 + x, j + y, color.getRGB());
            }
            textArea.append(showingHDValue.toString() + newLine);
        }
        Row row;
        if (!listOfHDValues.isEmpty()) {
            int lastSlahs = inputImageName.lastIndexOf("\\");
            int lastDot = inputImageName.lastIndexOf(".");
            textArea.append(inputImageName.substring(lastSlahs + 1, lastDot) + "=" + listOfHDValues.size() + newLine);
            textArea.append("======================================" + newLine);
            row = mainSheet.createRow(rowNumber);
//            row.createCell(0)
            row.createCell(1).setCellValue(inputImageName.substring(lastSlahs + 1, lastDot));
            row.createCell(2).setCellValue(listOfHDValues.size());
            rowNumber++;
        }

        if (!listOfHDValues.isEmpty()) {
            inputImageWithFoundTemplateList.add(lastInputImageWithFoundTemplate);
            inputImageMap.get(inputImageName).setSearchResultImage(lastInputImageWithFoundTemplate);
        }
    }

    public void endShow() {
        calculateButton.setEnabled(true);
        try {
//            if (lastInputImageWithFoundTemplate != null) {
//                inputImageWithFoundTemplateList.add(lastInputImageWithFoundTemplate);
//            }
            String fileName;
            File directory = new File("image/results/");
            for (File file : directory.listFiles()) {
                FileDeleteStrategy.FORCE.delete(file);
            }
            for (BufferedImage image : inputImageWithFoundTemplateList) {
                fileName = "image/results/" + System.currentTimeMillis() + ".bmp";
                ImageIO.write(image, "bmp", new File(fileName));
            }
            FileOutputStream outputStream = new FileOutputStream("results/ProcesResult" + System.currentTimeMillis() + ".xlsx");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if (inputImageList != null) {
            if (!inputImageList.isSelectionEmpty()) {
                int inputImageSelectedIndex = inputImageList.getSelectedIndex();
                inputImageList.clearSelection();
                inputImageList.setSelectedIndex(inputImageSelectedIndex);
            }
        }
    }

    private BufferedImage deepCopy(BufferedImage bi) {
        BufferedImage convertedBufferedImage=new BufferedImage(bi.getWidth(),bi.getHeight(),BufferedImage.TYPE_3BYTE_BGR);
        convertedBufferedImage.getGraphics().drawImage(bi,0,0,null);
        return convertedBufferedImage;
//        ColorModel cm = bi.getColorModel();
//        boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
//        WritableRaster raster = bi.copyData(null);
//        return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
    }
}
